#!/usr/bin/env ruby
require 'rubygems'
require 'osx/cocoa'
require 'growl'
require 'net/http'
require 'rexml/document'

uri = "/api/feed/home?format=xml"
username = nil
key = nil
demo = false
sticky = false

ARGV.each do |arg|
    case arg.downcase
    when '-demo', '-public'
        demo = true
        uri = "/api/feed/public?format=xml"
    when /^-(user|username|login)=(.*)$/
        username = $2
    when /^-(key|remotekey|apikey)=(.*)$/
        key = $2
    when '-sticky'
        sticky = true
    end
end

if username.nil? or key.nil?
    puts "Username and Remotekey are mandatory"
    exit
end

last = nil
growl = Growl::Notifier.alloc.init
growl.start('FriendFeed', ['new'])

Thread.new do
    loop do
        Net::HTTP.start('friendfeed.com') do |http|
            # Get feed
            request = Net::HTTP::Get.new(uri)
            # request = Net::HTTP::Get.new('/api/feed/home?format=xml')
            request.basic_auth(username, key)
            response = http.request(request)
            xml = REXML::Document.new(response.body)

            # Iter entries
            xml.root.elements.each('entry') do |entry|
                next if entry.elements['hidden'].text.downcase != 'false'
                # If first launch or first item has not changed
                break if last.nil? or entry.elements['id'].text == last

                if entry.elements['media']
                    entry.elements.each('media') do |media|
                        growl.notify('new', 
                            entry.elements['user/name'].text,
                            media.elements['title'].text,
                            media.elements['content/url'].text,
                            sticky, 0, media.elements['thumbnail/url'].text, true)
                    end
                else
                    growl.notify('new', 
                        entry.elements['user/name'].text,
                        entry.elements['title'].text,
                        entry.elements['link'].text,
                        sticky, 0, entry.elements['service/iconUrl'].text)
                end
                # break
            end
            
            # Set last and sleep
            last = xml.root.elements['entry/id'].text;
            sleep (demo ? 5 : 30)
        end
    end
end.run

OSX::NSApplication.sharedApplication
OSX::NSApp.run